<template>
  <!-- 后台登录主容器 -->
  <div class="login-container">
    <el-card class="login-card">
      <h2>后台登录</h2>
      <el-form :model="form" ref="formRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin">登录</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="msg" :title="msg" type="error" show-icon style="margin-top: 20px;" />
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const form = ref({ username: '', password: '' })
const formRef = ref(null)
const msg = ref('')
const router = useRouter()

// 登录方法
async function onLogin() {
  const res = await fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ...form.value, action: 'login' })
  })
  const data = await res.json()
  if (data.success) {
    msg.value = ''
    // 登录成功后设置 localStorage 标记，供中间件识别
    if (process.client) {
      localStorage.setItem('isAdminLogin', '1')
    }
    // 跳转到后台首页
    router.push('/admin')
  } else {
    msg.value = data.message || '登录失败'
  }
}

// 重置表单
function onReset() {
  form.value = { username: '', password: '' }
  if (formRef.value) formRef.value.clearValidate && formRef.value.clearValidate()
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}
.login-card {
  width: 350px;
  padding: 30px 20px;
}
</style> 